package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.*;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 部门表服务实现类
 */
@Service
public class RoleServiceImpl implements RoleService {


    @Autowired
    private RoleMapper roleMapper;

    /**
     * 分页查询
     * @param roledto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResponse<RoleVo> pageroles(RoleDto roledto, Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum,pageSize);
        Role relo = BeanUtil.toBean(roledto, Role.class);

        Page<Role> roles = roleMapper.pageroles(relo);
        PageResponse<RoleVo> roleVoPageResponse = PageResponse.of(roles, RoleVo.class);
        return roleVoPageResponse;
    }

    @Override
    public void addRole(RoleDto roledto) {
        Role relo = BeanUtil.toBean(roledto, Role.class);
        roleMapper.addRole(relo);
    }

    @Override
    public List<String> findCheckedroles(Long roleId) {
        return roleMapper.findCheckedroles(roleId);
    }

    @Override
    public void updateroles(RoleDto roledto) {

        Role role = BeanUtil.toBean(roledto, Role.class);
        //TODO 判断是否有用户绑定了该角色

        //判断用户点击的是编辑菜单还是编辑角色和禁用
        if (ObjectUtil.isEmpty(roledto.getCheckedResourceNos())){
            //编辑禁用
            roleMapper.updateroles(role);
        }else {
            //如果是菜单编辑就先把所有菜单都删除 然后在批量添加
            roleMapper.deleteRoleResource(role.getId());
            String[] checkedResourceNos = roledto.getCheckedResourceNos();
            //数组转集合  批量插入
            List<String> list = Arrays.asList(checkedResourceNos);
            List<RoleResource> roleresourcesList =  new ArrayList<>();
            list.forEach(item->{
                RoleResource roleResource = new RoleResource();
                roleResource.setResourceNo(item);
                roleResource.setRoleId(role.getId());
                roleResource.setDataState(SuperConstant.DATA_STATE_0);
                roleresourcesList.add(roleResource);
            });
            roleMapper.addRoleResource(roleresourcesList);
        }

    }

    @Override
    public void deleteRole(String roleId) {
        roleMapper.deleteRole(roleId);
    }

    @Override
    public List<RoleVo> xialakuang() {
        List<RoleVo> roleVo = roleMapper.xialakuang();
        return roleVo;
    }

}
